﻿using System;
using System.Collections;
using System.Web.Mvc;
using Huirui.Cavan.Application.MainBoundedContext.SalesModule;
using Huirui.Cavan.Domain.MainBoundedContext.SalesModule;
using Huirui.Cavan.Domain.MainBoundedContext.SearchModule;
using Huirui.Cavan.Presentation.Seedwork;
using Huirui.Cavan.Presentation.ViewModel.SalesModule;
using Huirui.Cavan.Core.Extension;
using Huirui.Cavan.Domain.Seedwork;
using Newtonsoft.Json;
using System.Collections.Generic;
using Huirui.Cavan.Application.MainBoundedContext.SystemModule;
using Huirui.Cavan.Application.MainBoundedContext.StockModule;

namespace Huirui.Cavan.Presentation.Controller.SalesModule
{
	#region SalesOrder

    public class SalesOrderController : EntityController<SalesOrder, string, SalesOrderSearch, ISalesOrderViewModel, ISalesOrderAppService>, ISalesOrderController
    {
        private IProjectAppService ProjectAppService { get; set; }
        private ICustomerAppService CustomerAppService { get; set; }
        private IWareHouseAppService WareHouseAppService { get; set; }
        private IStockAppService StockAppService { get; set; }
        private IEmployeeAppService EmployeeAppService { get; set; }

        public override string ControllerName
        {
            get { return ControllerConst.SALESORDER; }
        }

        public override bool UseDenied
        {
            get { return false; }
        }

        public SalesOrderController()
        {
            this.Model = ModelFactory.CreateModel<ISalesOrderViewModel>();
        }

        [ActionName(ActionConst.ADD)]
        [HttpGet]
        [ActionPermissionAttribute(Name = "salesorder_query")]
        public ActionResult AddSalesOrder(string id)
        {
            if (id.IsNotEmpty())
            {
                this.Model.Item = this.AppService.GetById(id);
            }
            else
            {
                this.Model.Item = new SalesOrder();
                this.Model.Item.SaleDate = DateTime.Now;
                this.Model.Item.DeliveryDate = DateTime.Now;
                this.Model.Item.Id = "";
            }

            return View("~/Views/Sales/v1/addSalesOrder.cshtml", this.Model);
        }

        [ActionName(ActionConst.ADD)]
        [HttpPost]
        [ActionPermissionAttribute(Name = "salesorder_edit")]
        public JsonResult AddSalesOrder(SalesOrderViewModel model)
        {
            BoolResult jsonResult = null;
            model.Item.CheckType = (SalesIdentifier.CheckType)model.CheckType;
            model.Item.SalesOrderDetails = JsonConvert.DeserializeObject<IList<SalesOrderDetail>>(model.SalesOrderDetails);

            BoolGenericResult<SalesOrder> result = this.AppService.AddOrUpdate(model.Item);
            jsonResult = new BoolResult(result.IsSuccess, result.Messages);

            return Json(jsonResult, "application/json");
        }
    }
	#endregion
}